package com.treasure.mall.biz.repository.order;

import com.treasure.mall.biz.entity.order.OrderItemPO;
import com.treasure.mall.zbq.common.ienum.order.OrderEnums;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * @author allan
 * @version 1.0.0
 * @date 2020/6/11
 */
@Repository
public interface OrderItemRepository extends JpaRepository<OrderItemPO, Long> {
    @Query("update OrderItemPO item set item.afterSaleStatus=?2 where item.id=?1")
    @Modifying
    @Transactional
    void updateAfterSale(Long id, OrderEnums.AfterSaleStatus afterSaleStatus);

    @Query("update OrderItemPO item set item.deliverStatus=?1,item.receiveTime=?2 where item.id=?3")
    @Modifying
    @Transactional
    void updateDeliverStatus(OrderEnums.DeliverStatus deliverStatus, LocalDateTime receiveTime, Long id);

    @Query("select coalesce(sum(item.num),0) from OrderItemPO item " +
            "where item.subOrderPO.orderPO.userPO.userId=?1 and item.goodsInfo.goodsId=?2 " +
            "and item.subOrderPO.orderPO.payStatus=?3 ")
    int buyCount(Long userId, Long productId, OrderEnums.PayStatus payStatus);

    /**
     * @param userId
     * @param productId
     * @param status
     * @return
     */
    @Query("select coalesce(sum(item.num),0) from OrderItemPO item " +
            "where item.subOrderPO.orderPO.userPO.userId=?1 and item.goodsInfo.goodsId=?2 " +
            "and item.subOrderPO.status=?3 and item.subOrderPO.orderPO.payStatus=?4")
    int buyCountByStatus(Long userId, Long productId, OrderEnums.Status status, OrderEnums.PayStatus payStatus);
}
